package chapter_2.demo_3;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author: hero生仔
 * 测试：编写灵活的 prettyPrintApple 方法
 * <p>
 * 需求：要求能接受一个Apple的List，并可以对它参数化，以多种方式根据苹果生成一个String输出（类似多个可定制的toString()方法）。例如，你可以告诉 prettyPrintApple 方法只打印每个苹果的重量，此外，
 * 可以让prettyPrintApple 方法分别打印每个苹果，然后说明他是重的还是轻的。
 */
public class Apple {
    Integer weight;
    String color;

    public Apple(Integer weight, String color) {
        this.weight = weight;
        this.color = color;
    }

    public static String howHeavy(Apple apple) {
        return "this apple is " + apple.weight + "g";
    }

    public static String isHeavy(Apple apple) {
        String str = apple.weight > 150 ? "heavy" : "light";
        return "A " + str + " " + apple.color + " apple ";
    }

    /**
     * 相对于demo_1，我们需要更加抽象，引入类型参数T，然后我们不仅可以接受苹果的还可以接受其他的水果的。
     */
    public static <T> void prettyPrintApple(List<T> inventory, Predicate<T> p) {
        for (T fruit : inventory) {
            String result = p.test(fruit);
            System.out.println(result);
        }
    }

    public interface Predicate<T> {
        String test(T t);
    }
}

class Main {
    public static void main(String[] args) {
        Apple apple01 = new Apple(155, "red");
        Apple apple02 = new Apple(80, "green");
        List<Apple> list = new ArrayList<>();
        list.add(apple01);list.add(apple02);
        Apple.prettyPrintApple(list,Apple::isHeavy);
        Apple.prettyPrintApple(list,Apple::howHeavy);
    }
}
